<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\Queue;
use app\common\library\Ems;
use app\common\library\Redis;
use app\common\library\Sms;
use app\common\model\CollectionCode;
use app\common\model\Commission;
use app\common\model\UserVerified;
use fast\Random;
use think\Db;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
    	$userInfo = $this->auth->getUserinfo();
    	$userId = $this->auth->id;
    	$where = [
    	    'user_id' => $userId,
		    'status' => Commission::STATUS_Y
	    ];
    	$userInfo['commission'] = Db::name('commission')->where($where)->sum('amount');
    	$where['create_time'] = ['egt', strtotime(date('Y-m-d'), strtotime('-1 days'))];
	    $userInfo['day_commission'] = Db::name('commission')->where($where)->sum('amount');
	    
	    $userInfo['verified'] = Db::name('userVerified')->where(['user_id' => $userId])->find();
	    $levelList = \app\admin\model\User::$levelList;
	    $userInfo['level_text'] = $levelList[$userInfo['level']] ??'普通会员';
	    
	    $recommend = Db::name('userLayer')->alias('l')
		    ->join('user u', 'l.parent_id = u.id', 'left')
		    ->where(['l.user_id' => $userId,'l.layer' => 1])
		    ->field('u.mobile')
		    ->find();
	    
	    $userInfo['recommend'] = $recommend ? $recommend['mobile'] : '';
    	
        $this->success('', $userInfo);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     */
    public function register()
    {
        $username = $this->request->post('username','u'.time().mt_rand(1000, 9999));
        $password = $this->request->post('password');
        $email = $this->request->post('email', '');
        $mobile = $this->request->post('mobile');
	    $captcha = $this->request->post('captcha');
	    $recommendMobile = $this->request->post('recommend_mobile');
	    
	    $data = [];
	    if($recommendMobile) {
	    	if (!Validate::regex($recommendMobile, "^1\d{10}$")) {
			    $this->error(__('推荐人手机号不正确'));
		    }
	    	
	    	$recommend = \app\common\model\User::getByMobile($recommendMobile);
	    	!$recommend && $this->error('推荐人不存在');
	    	
	    	if($recommend['level'] == 0) {
	    		$this->error('该用户没有推荐权限');
		    }
	    	
	    	$data['recommend_user_id'] = $recommend['id'];
	    }
	    
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        
        if(!Validate::regex($password, "^\w{6,18}$")) {
        	$this->error('密码格式不正确');
        }
	
	    if (!Sms::check($mobile, $captcha, 'register')) {
		    $this->error(__('Captcha is incorrect'));
	    }
        $ret = $this->auth->register($username, $password, $email, $mobile, $data);
        if ($ret) {
        	
        	//添加推荐人关系队列任务
	        if($recommendMobile && isset($recommend)) {
		        Queue::addTask('addUserLayer', [
			        'user_id' => $this->auth->id,
			        'parent_id' => $recommend['id']
		        ]);
	        }
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error('昵称已经存在了');
            }
	        $user->nickname = $nickname;
        }
	
        $mobile = $this->request->post('mobile');
	    if ($mobile) {
		    $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
		    if ($exists) {
			    $this->error('手机号码已经存在了');
		    }
		    $user->mobile = $mobile;
	    }
        
        if($avatar) {
        	$user->avatar = $avatar;
        }
        
        
        $res = $user->save();
        if($res) {
        	$this->success('修改成功', $this->auth->getUserinfo());
        } else {
	        $this->error('修改出错');
        }
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("password");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
	
	/**
	 * 收款码
	 */
    public function collectionCode() {
    	$userId = $this->auth->id;
    	$aliImage = $this->request->post('ali_image');
	    $weixinImage = $this->request->post('weixin_image');
	    if(!$aliImage && !$weixinImage) {
	    	$this->error('请上传支付宝或微信收款码');
	    }
	    
	    $model = new CollectionCode();
	    $row = $model->where(['user_id' => $userId])->find();
	    
	    $data = [
		    'ali_image' => $aliImage,
		    'weixin_image' => $weixinImage
	    ];
	    if($row) {
	    	$res = $model->save($data, ['id' => $row['id']]);
	    } else {
	    	$data['user_id'] = $userId;
	    	$res = $model->isUpdate(false)
			    ->save($data);
	    }
	    
	    if($res !== false) {
	        $this->success('保存成功');
	    } else {
	    	$this->error('保存出错', $model->getError());
	    }
    }
    
    public function myCode() {
    	$userId = $this->auth->id;
    	$row = Db::name('CollectionCode')
		    ->where(['user_id' => $userId])
		    ->find();
    	$this->success('查询成功', $row);
    }
    
    /**
     * 实名认证
     */
    public function authentication() {
    	$userId = $this->auth->id;
    	
	    $trueName = $this->request->post('true_name');
	    !$trueName && $this->error('请填写真实姓名');
	    
    	$idcard = $this->request->post('idcard');
    	!$idcard && $this->error('请填写身份证号码');
    	
	    $images = $this->request->post('images');
	    $imageArr = explode(',', $images);
	    if(count($imageArr) != 3) {
	    	$this->error('请上传全部图片');
	    }
		   
	    $model = new UserVerified();
	    $row = $model->where(['user_id' => $userId])->find();
	    $data = [
	        'user_id' => $userId,
		    'true_name' => $trueName,
		    'card_no' => $idcard,
		    'images' => $images,
	    ];
	    
	    if($row) {
	    	if($row['status'] == 3) {
	    		$data['status'] = 1;
		    }
	    	
	    	$res = $model->save($data, ['id' => $row['id']]);
	    } else {
	    	$res = $model->isUpdate(false)->save($data);
	    }
	    
	    if($res !== false) {
	    	$this->success('保存成功');
	    } else {
	    	$this->error('保存出错');
	    }
    }
}
